﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.InteropServices;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;


namespace NETCommon.Files
{ 
    public class NAppFile
    {
        private XDocument _configDoc = null;
        private string _getAppSettings = null;
        private string _path = String.Empty;

        public string getAppSettings
        {
            get { return _getAppSettings; }
            set { _getAppSettings = value; }
        }
        public NAppFile(string FilePath)
        {
            loadConfigurationFile(FilePath);
        }
        private XElement getDescendant(string key)
        {

            XElement elem = null;

            foreach (XElement setting in _configDoc.Descendants("appSettings").Elements())
            {
                XAttribute keyAtt = setting.Attribute("key");
                if (keyAtt.Value == key) elem = setting;
            }


            return elem;

        }
        public void loadConfigurationFile(string path)
        {
            _configDoc = new XDocument();
            _path = path;
            _configDoc = XDocument.Load(_path);
        }
        public string getAppSettingValue(string key)
        {
            XElement getAppSettings = getDescendant(key);
            string configValue = getAppSettings.Attribute("value").Value;
            return configValue.ToString();
        }
        public void setAppSettingValue(string key, string newValue)
        {

            XElement getAppSettings = getDescendant(key);

            getAppSettings.SetAttributeValue("value", newValue);

            _configDoc.Save(_path);

        }
        public void Add(string key, string Value)
        {

            XElement element = new XElement("add", new XAttribute("key", key), new XAttribute("value", Value));

            XElement addElement = _configDoc.Descendants("appSettings").Elements().Last();

            addElement.AddAfterSelf(element);

            _configDoc.Save(_path);
        }
        public void Remove()
        {
            File.Delete(_path);
            StreamWriter SW = File.CreateText(_path);
            SW.WriteLine(@"<?xml version=""1.0"" encoding=""utf-8""?>");
            SW.WriteLine("<configuration>");
            SW.WriteLine("  <appSettings>");
            SW.WriteLine(@"    <add key=""CustomizeEn"" value=""0"" />");
            SW.WriteLine("  </appSettings>");
            SW.WriteLine("</configuration>");
            SW.Close();
        }
        public void RemoveAt(string key)
        {
            XElement getAppSettings = getDescendant(key);
            getAppSettings.Remove();
            _configDoc.Save(_path);
        }

    }
    
}
